package com.itheima.web;

import com.itheima.pojo.Brand;
import com.itheima.pojo.User;
import com.itheima.service.BrandService;
import com.itheima.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
    private  UserService service = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String remeber = request.getParameter("remeber");

        User user = service.login(username, password);
        if(user!=null){
            //判断用户是否登录成功
            if(("1").equals(remeber)){
                //勾选了，发送Cookie
                //创建Cookie对象
                Cookie c_username=new Cookie("username",username);
                Cookie c_password=new Cookie("password",password);

                //设置Cookie存活时间
                c_username.setMaxAge(60*60*7);
                c_password.setMaxAge(60*60*7);
                //转发到客户端
                response.addCookie(c_username);
                response.addCookie(c_password);
            }
            //将登陆成功后的username,password存储到session中
            HttpSession session = request.getSession();
            session.setAttribute("user",user);//存储对象
            //登陆成功，重定向到查询所有
            String context=request.getContextPath();//动态获取虚拟目录
            response.sendRedirect(context+"/selectAllServlet");
        }
        else {
            request.setAttribute("login_msg","用户名或密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request,response);//转发request域中数据
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}